#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <memory>
#include "thread.hpp"

uint16_t serverport;
std::string serverip;

void usage(std::string proc)
{
    std::cerr << "\nUsage: " << proc << " serverIp serverPort\n"
              << std::endl;
}

void *udpSend(void *args)
{
    int sock = *(int *)((ThreadData *)args)->args_;
    std::string name = ((ThreadData *)args)->name_;

    std::string massage;
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    while (true)
    {
        usleep(1);
        std::cerr << "请输入你的信息# ";
        std::getline(std::cin, massage);
        if (massage == "quit")
        {
            break;
        }
        sendto(sock, massage.c_str(), sizeof(massage), 0, (struct sockaddr *)&server, sizeof(server));
    }

    return nullptr;
}

void *udpRecv(void *args)
{
    int sock = *(int *)((ThreadData *)args)->args_;
    std::string name = ((ThreadData *)args)->name_;

    char buffer[1024];
    while (true)
    {
        memset(buffer, 0, sizeof(buffer));
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t s = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&temp, &len);
        if (s > 0)
        {
            buffer[s] = '\0';
            std::cout << "server said:" << buffer << std::endl;
        }
    }
}

int main(int argc, char *argv[])
{
    if (argc < 3)
    {
        usage(argv[0]);
        exit(1);
    }

    // 创建套接字
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        std::cout << "socket error" << std::endl;
    }

    serverport = atoi(argv[2]);
    serverip = argv[1];
    // 客户端一般不绑定，因为不能保证在用户电脑上我们制定的文件是否已经被绑定
    // 所以客户端一般让操作系统随机获取端口
    std::unique_ptr<Thread> sender(new Thread(1, udpSend, (void *)&sock));
    std::unique_ptr<Thread> receiver(new Thread(2, udpRecv, (void *)&sock));

    sender->Start();
    receiver->Start();

    sender->join();
    receiver->join();

    close(sock);

    return 0;
}